TARGETS := proc-receive
PKG := golang.aliyun-inc.com/agit/agit/proc-receive-hook

VENDOR_EXISTS=$(shell test -d vendor && echo 1 || echo 0)
ifeq ($(VENDOR_EXISTS), 1)
    GOBUILD := GO111MODULE=on CGO_ENABLED=0 go build -trimpath -mod=vendor -o proc-receive
    GOTEST := GO111MODULE=on go test -mod=vendor
else
    GOBUILD := GO111MODULE=on CGO_ENABLED=0 go build -trimpath -o proc-receive
    GOTEST := GO111MODULE=on go test
endif
GOBUILD_LINUX_64 := env GOOS=linux GOARCH=amd64 $(GOBUILD)
GOBUILD_LINUX_32 := env GOOS=linux GOARCH=386 $(GOBUILD)

# Returns a list of all non-vendored (local packages)
LOCAL_PACKAGES = $(shell go list ./... | grep -v -e '^$(PKG)/vendor/')

-include VERSION-FILE

define message
	@echo "### $(1)"
endef

all: $(TARGETS)

VERSION-FILE: FORCE
	$(call message,Generate version file)
	@/bin/sh ./VERSION-GEN

LDFLAGS := -ldflags "-X $(PKG)/version.Version=$(VERSION)"
RELEASE_LDFLAGS := -ldflags "-X $(PKG)/version.Version=$(VERSION) -s -w"

build: $(TARGETS)

proc-receive: $(shell find . -name '*.go') | VERSION-FILE
	$(call message,Building $@)
	$(GOBUILD) $(LDFLAGS) -o $@

test: golint ut it

golint:
	$(call message,Testing using golint for coding style)
	@golint $(LOCAL_PACKAGES)

ut: $(TARGETS)
	$(call message,Running unit tests)
	$(GOTEST) -cover -v $(PKG)/...

it: $(TARGETS)
	$(call message,Running integration tests)
	@make -C test

linux: linux-64

linux-64: _build/linux-64/proc-receive

_build/linux-64/proc-receive: $(shell find . -name '*.go')
	@$(call message,Building $@)
	@mkdir -p $(shell dirname $@)
	$(GOBUILD_LINUX_64) $(RELEASE_LDFLAGS) -o $@

clean:
	rm -f $(TARGETS)
	rm -rf "_build/"

.PHONY: FORCE
.PHONY: all build test ut it linux linux-64 clean
